package de.upb.messerschmidt.set;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.upb.messerschmidt.set.entity.Message;
import de.upb.messerschmidt.set.entity.Person;
import de.upb.messerschmidt.set.jdo.PMF;

/**
 * Gets {@link Message}s from an user ({@link Person}) via HttpPost and persists
 * it.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class SendMessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String message = req.getParameter("msg");
		String userString = req.getParameter("from");
		String contactString = req.getParameter("target");

		if (userString != null && contactString != null && message != null) {
			Person user = null;
			Person contact = null;

			PersistenceManager pm = PMF.get().getPersistenceManager();

			Query query = pm.newQuery(Person.class);
			query.setFilter("name == nameParam && prename == prenameParam");
			query.declareParameters("String nameParam, String prenameParam");
			query.setOrdering("name desc");

			String[] userArr = nameParser(userString);
			List<Person> users = (List<Person>) query.execute(userArr[0],
					userArr[1]);

			if (!users.isEmpty()) {
				user = users.get(0);
			}

			String[] contactArr = nameParser(contactString);
			List<Person> contacts = (List<Person>) query.execute(contactArr[0],
					contactArr[1]);

			if (!contacts.isEmpty()) {
				contact = contacts.get(0);
			}

			if (!(user == null && contact == null && message.equals(""))) {
				Message msg = new Message(user.getName() + ", "
						+ user.getPrename(), contact.getName() + ", "
						+ contact.getPrename(), message);

				try {
					pm.makePersistent(msg);

					resp.setStatus(200);
					resp.getWriter().println("Message saved successfully");
				} finally {
					pm.close();
				}
			} else {
				resp.setStatus(400);
				resp.getWriter().println("User or Target not found");
			}
		} else {
			// If the values are not null save a new msg else {
			resp.setStatus(400);
			resp.getWriter().println("Error: Missing parameters");
		}
	}

	private String[] nameParser(String user) {
		return user.split(", ");
	}
}
